from django.shortcuts import render
from django.views import View
from django.http import JsonResponse

import json

from book.models import BookInfo
# Create your views here.


class BookDetailView(View):
    """
    显示指定图书：GET
    修改指定图书：PUT
    删除指定图书：DELETE
    """
    def get(self, request, pk):
        """
        新增图书
        路由：GET  /books/<pk>/
        """
        # 省略参数校验
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({'code': 404, 'errmsg': '数据不存在'})
        return JsonResponse({
            'code': 200,
            'errmsg': '查询成功',
            'book':{
                "id": book.id,
                "commentcount": book.commentcount,
                "pub_date": book.pub_date,
                "readcount": book.readcount,
                "name": book.name,
                "image": str(book.image)
            }
        })

    def put(self, request, pk):
        """
        修改图书
        路由：PUT  /books/<pk>/
        """
        json_dict = json.loads(request.body.decode())
        commentcount = json_dict.get('commentcount')
        readcount = json_dict.get('readcount')
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({'code': 404, 'errmsg': '数据不存在'})

        book.readcount = readcount
        book.commentcount = commentcount
        book.save()

        return JsonResponse({
            'code': 200,
            'errmsg': '修改数据成功',
            'book':{
                "id": book.id,
                "commentcount": book.commentcount,
                "pub_date": book.pub_date,
                "readcount": book.readcount,
                "name": book.name,
                "image": str(book.image)
            }
        })

    def delete(self, request, pk):
        """
        删除
        路由：DELETE  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({'code': 404, 'errmsg': '数据不存在'})

        book.delete()
        return JsonResponse({'code': 200, 'errmsg': '删除数据成功'})


class BookListView(View):
    """
    新增图书：POST
    显示所有图书：GET
    """
    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        # 获取参数
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')
        pub_date = json_dict.get('pub_date')

        # 校验参数：省略

        # 数据保存
        try:
            book = BookInfo.objects.create(
                name=name,
                pub_date=pub_date
            )
        except BookInfo.DoesNotExist:
            return JsonResponse({'code': 404, 'errmsg': '数据库保存失败'})
        return JsonResponse({'code': 200, 'errmsg': '添加数据成功'})

    def get(self, request):
        """
        显示所有图书
        路由：GET /books/
        """
        books = BookInfo.objects.all()
        book_list = []
        for book in books:
            book_list.append({
                "id": book.id,
                "commentcount": book.commentcount,
                "pub_date": book.pub_date,
                "readcount": book.readcount,
                "name": book.name,
                "image": str(book.image)
            })
        return JsonResponse({'code': 200, 'errmsg': '查询数据成功', 'books': book_list})


from book.serializer import BookInfoSerializer
from book.models import BookInfo
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request

class BookInfoAPIView(APIView):

    def get(self, request):
        books = BookInfo.objects.all()
        serializer = BookInfoSerializer(instance=books, many=True)
        return Response(serializer.data)

    def post(self, request):
        data = request.data
        serializer = BookInfoSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response({'errmsg': '数据错误'})
